import WebSocket from 'ws'
import { isEmpty } from 'lodash'
import { jobListUrl, makeRequest, sleep } from './utils'
import fs from 'fs'
import path from 'path'

const args = {
    page: 1,
    maxPage: 9,
    // 长沙
    city: '101250100',
    // 前端开发
    position: '100901'
}

const ws = new WebSocket('ws://localhost:8888/hook?id=A')

const hookData = async (cookie: string): Promise<boolean> => {
    const { page, city, position } = args
    const url = jobListUrl(page, city, position)
    const data: any = await makeRequest(url, cookie)
    const jobs = data.zpData?.jobList || []
    // 拿到数据开始写入
    if (!isEmpty(jobs)) {
        const jobList = JSON.stringify(jobs, null, 2)
        const dirPath = path.resolve('.', 'boss')
        const savePath = path.resolve(dirPath, `${page}.json`)
        if (!fs.existsSync(dirPath)) {
            fs.mkdirSync(dirPath, { recursive: true })
        }
        fs.writeFileSync(savePath, jobList, 'utf-8')
        console.log(`写入第${page}页数据`)
        return true
    }
    // 重新生成cookie
    const msg = JSON.stringify({ target: 'B' })
    ws.send(msg)
    return false
}

const onMessage = async (msg: string) => {
    const jsonData = JSON.parse(msg)
    // 拿到cookie
    const cookie = jsonData.data
    while (args.page <= args.maxPage) {
        const isActive = await hookData(cookie)
        // 等待下一次cookie生成
        if (!isActive) {
            console.log('正在重新生成cookie')
            break
        }
        args.page++
        // 休眠5s防止爬取过快
        await sleep(5 * 1000)
    }
}

ws.on('message', onMessage)
